<template>
  <div class="container">
    <el-row>
      <el-col class="top-search">
        <el-button type="primary" @click="add">
          {{ $t('new_reward_event') }}
        </el-button>
      </el-col>

      <el-col class="p-t-20">
        <el-table
          v-loading="listLoading"
          :data="listData"
          border
          fit
          highlight-current-row
        >
          <el-table-column
            :label="$t('serial_number')"
            width="60"
            align="center"
          >
            <template slot-scope="scope">
              <span>
                {{
                  (listQuery.pageNum - 1) * listQuery.pageSize +
                    scope.$index +
                    1
                }}
              </span>
            </template>
          </el-table-column>

          <el-table-column
            :label="$t('id')"
            prop="id"
            align="center"
            width="120"
          />

          <el-table-column :label="$t('creation_date')" align="center">
            <template slot-scope="{ row }">
              <span> {{ row.createTime | fmtdate }} </span>
            </template>
          </el-table-column>

          <el-table-column
            :label="$t('event_name')"
            prop="name"
            align="center"
            width="120"
          />
          <el-table-column
            :label="$t('rewarding_method')"
            prop="fuck"
            align="center"
          >
            <template slot-scope="{ row }">
              <el-tag type="success" v-if="row.type == TYPE_MAP.AUTO">
                {{ $t('automatic') }}
              </el-tag>
              <el-tag type="info" v-if="row.type == TYPE_MAP.Manual">
                {{ $t('manual') }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column :label="$t('reward_time')" align="center">
            <template slot-scope="{ row }">
              <span v-if="row.rewardTime">
                {{ row.rewardTime | fmtdate }}
              </span>
            </template>
          </el-table-column>

          <el-table-column
            :label="$t('list_of_winners_distribute_amount')"
            align="center"
          >
            <template slot-scope="{ row }">
              <span>
                <el-button size="mini" type="primary">
                  <a :href="row.url" download>{{ $t('download') }}</a>
                </el-button>
              </span>
            </template>
          </el-table-column>

          <el-table-column
            :label="$t('system_notification')"
            prop="fuck"
            align="center"
          >
            <template slot-scope="{ row }">
              <span>
                <span> {{ noticeLanMap[row.msgType] }} </span>
                <el-button size="mini" type="primary" @click="view(row)">
                  {{ $t('view') }}
                </el-button>
              </span>
            </template>
          </el-table-column>

          <el-table-column
            :label="$t('number_of_award_exceptions')"
            prop="fuck"
            align="center"
          >
            <template slot-scope="{ row }">
              <span>
                <span> {{ row.errorMemberNum || 0 }} </span>
                <el-button v-if="row.errorMemberNum" size="mini" type="primary"
                 @click="viewErrorArray(row.errorMemberIds)">
                  {{ $t('view') }}
                </el-button>
              </span>
            </template>
          </el-table-column>

          <el-table-column :label="$t('operation')" align="center">
            <template slot-scope="{ row }">
              <el-button
                :disabled="btnLoading && row.id == currentObj.id"
                :loading="btnLoading && row.id == currentObj.id"
                type="danger"
                v-if="!row.isReward && row.type == TYPE_MAP.Manual"
                @click="beforeGive(row)"
              >
                {{ $t('distribute_reward') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div v-if="total > 0" class="block fr">
          <el-pagination
            :current-page="listQuery.pageNum"
            :page-sizes="[15, 20, 30]"
            :page-size="listQuery.pageSize"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="val => handlePageChange(val, 'pageSize')"
            @current-change="val => handlePageChange(val, 'pageNum')"
          />
        </div>
      </el-col>
    </el-row>

    <!-- 新建项目 -->
    <el-dialog
      :visible.sync="show.add"
      :title="$t('new_reward_event')"
      width="800px"
    >
      <el-form label-width="200px">
        <el-form-item :label="$t('event_name')">
          <el-input
            v-model="form.name"
            size="small"
            :maxlength="MAX_LENGTH"
            class="w-400"
          >
            <template slot="append"
              >{{ (form.name && form.name.length) || 0 }}/{{
                MAX_LENGTH
              }}</template
            >
          </el-input>
          <p class="tip">{{ $t('pay_attention_to_the_language') }}</p>
        </el-form-item>

        <el-form-item :label="$t('list_of_winners_distribute_amount')">
          <el-upload
            ref="referenceUpload"
            :on-change="handleChange"
            :limit="1"
            :auto-upload="false"
            :show-file-list="false"
            class="import-btn"
            action=""
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
          >
            <el-button type="primary" size="small">
              {{ $t('import_winners_list') }}
            </el-button>
          </el-upload>
          <el-tag v-if="form.url" type="success">{{ $t('imported') }}</el-tag>
          <el-tag v-if="!form.url" type="info">{{ $t('not_imported') }}</el-tag>
          <el-button type="primary" size="small" @click="downloadTemp">
            {{ $t('download_excel_template') }}
          </el-button>
          <p class="tip">{{ $t('the_format_of_the_imported_excel') }}</p>
        </el-form-item>

        <el-form-item :label="$t('rewarding_method')">
          <el-radio-group v-model="form.type">
            <el-radio :label="TYPE_MAP.Manual">{{ $t('manual') }}</el-radio>
            <el-radio :label="TYPE_MAP.AUTO">{{ $t('automatic') }}</el-radio>
          </el-radio-group>
          <br />
          <el-date-picker
            v-if="form.type == 2"
            v-model="form.rewardTimeStr"
            :picker-options="expireTimeOption"
            type="datetime"
            align="right"
            value-format="yyyy-MM-dd HH:mm:ss"
            @focus="hideNowBtn"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('system_notification_settings')">
          <el-radio-group v-model="form.msgType">
            <el-radio :label="1">{{
              $t('send_chinese_system_notification')
            }}</el-radio>
            <el-radio :label="2">{{
              $t('send_english_system_notification')
            }}</el-radio>
            <el-radio :label="3">{{
              $t('send_khmer_system_notification')
            }}</el-radio>
          </el-radio-group>

          <el-input
            type="textarea"
            disabled
            :autosize="{ minRows: 3, maxRows: 5 }"
            v-model="form.msg"
            placeholder="ឧទាហរណ៌: អ្នកប្រើប្រាស់ជាទីស្រលាញ់ អបអរសាទរ ក្នុងកម្មវិធី【XXXXXXX（ឈ្មោះកម្មវិធី）】អ្នកបានឈ្នះរង្វាន់ចំនួន 【yyyyy（ចំនួនរង្វាន់）】សូមចូលពិនិត្យមើលកាបូបលុយក្នុង TNAOT APP របស់អ្នក សូមអរគុណ។"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :disabled="btnLoading"
          :loading="btnLoading"
          @click="beforeAdd"
          >{{ $t('confirm') }}</el-button
        >
      </span>
    </el-dialog>

    <!-- 发奖异常 -->
    <el-dialog
      :visible.sync="show.error"
      :title="$t('prize_exceptions')"
      width="800px"
    >
      <p> {{ $t('the_following_users_were_unsuccessful_in_issuing_prizes') }}: </p>
      <div class="p-t-20">
        <div class="error-item" v-for="item in errorArray" :key="item"> {{item}} </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="show.error = false">{{ $t('confirm') }}</el-button>
      </span>
    </el-dialog>

    <!-- 系统通知样式 -->
    <el-dialog
      :visible.sync="show.details"
      :title="$t('system_notification_template')"
      width="800px"
    >
      <div>
        {{ currentObj.msg }}
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="show.details = false">{{ $t('confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  rewardApi,
  rewardListApi,
  rewardAddApi,
  uploadFileNoCompressApi
} from '@/api/realization-audit.js';
import { isPast } from 'date-fns';
import { exportJsonToExcel } from '@/utils/excel/Export2Excel';

const MAX_LENGTH = 30;
const TYPE_MAP = {
  Manual: 1,
  AUTO: 2
};

export default {
  data() {
    return {
      MAX_LENGTH,
      TYPE_MAP,
      listLoading: false,
      btnLoading: false,
      noticeLanMap: {
        1: this.$t('chinese_notice'),
        2: this.$t('english_notice'),
        3: this.$t('khmer_notice')
      },
      listQuery: {
        pageNum: 1,
        pageSize: 20
      },
      listData: [],
      total: 0,
      show: {
        add: false,
        details: false,
        error: false
      },
      form: {
        name: null,
        type: 1, // 发奖方式: 1: 手动 2: 自动
        msgType: 3, // 1中 2英 3柬
        rewardTimeStr: null,
        msg: null,
        url: null
      },
      currentObj: {
        id: null,
        msg: null
      },
      errorArray: [],
      expireTimeOption: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; // 当天之后的时间可选
        }
      }
    };
  },

  watch: {
    'form.msgType': {
      handler() {
        const { msgType } = this.form;
        const map = {
          1: '示例：尊敬的用户，恭喜你在【XXXXXXX（项目名字）】中获得【yyyyy（发放数额）】的奖励，请前往APP钱包查询，感谢你的支持。',
          2: 'Example: Dear users, congratulations on getting the reward of [YYY (issued amount)] in [XXX (event name)], please go to your APP wallet to check, thank you for your support.',
          3: 'ឧទាហរណ៌: អ្នកប្រើប្រាស់ជាទីស្រលាញ់ អបអរសាទរ ក្នុងកម្មវិធី【XXXXXXX（ឈ្មោះកម្មវិធី）】អ្នកបានឈ្នះរង្វាន់ចំនួន 【yyyyy（ចំនួនរង្វាន់）】សូមចូលពិនិត្យមើលកាបូបលុយក្នុង TNAOT APP របស់អ្នក សូមអរគុណ។'
        };

        this.form.msg = map[msgType];
      }
    }
  },

  created() {
    this.search();
  },

  methods: {
    search() {
      this.listQuery.pageNum = 1;
      this.getList();
    },

    async getList() {
      if (this.listLoading) return;
      this.listLoading = true;

      try {
        const { state, result } = await rewardListApi(this.listQuery);
        this.listLoading = false;
        if (state == 1) {
          this.listData = result.list || [];
          this.total = Number(result.total) || 0;
        }
      } finally {
        this.listLoading = false;
      }
    },

    handlePageChange(val, name) {
      this.listQuery[name] = val;
      this.getList();
    },

    async beforeGive(row) {
      const action = await this.$confirm(
        this.$t('are_you_sure_about_the_bonus'),
        this.$t('tips'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      );

      if (action === 'confirm') {
        this.give(row);
      }
    },

    add() {
      this.form = {
        name: null,
        type: 1,
        msgType: 3,
        rewardTimeStr: null,
        msg: null,
        url: null
      };
      this.show.add = true;
    },

    view(row) {
      this.currentObj = row;
      this.show.details = true;
    },

    async give({ url, name, msg, id }) {
      if (this.btnLoading) return;
      this.btnLoading = true;
      const query = {
        id,
        url,
        name,
        msg
      };

      try {
        const { state, error_msg } = await rewardApi(query);
        if (state == 1) {
          this.$message.success(this.$t('operate_successfully'));
          this.getList();
        } else {
          this.$message.warning(error_msg);
        }
      } finally {
        this.btnLoading = false;
      }
    },

    handleChange(file) {
      const fileTemp = file.raw;
      this.$refs.referenceUpload.clearFiles();
      if (fileTemp) {
        if (
          fileTemp.type ==
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
          fileTemp.type == 'application/vnd.ms-excel'
        ) {
          this.uploadExcel(fileTemp);
        } else {
          this.$message.warning('incorrect_format_of_attachment');
        }
      } else {
        this.$message.warning('please_upload_the_attachment');
      }
    },

    async uploadExcel(file) {
      const formData = new FormData();
      formData.append('keyId', 'LTAIQ0IV2BcwuDYiYY');
      formData.append('keySecret', 'w8yBL68zkbtLlfD9ITLYhhoiy5fUjyYY');
      formData.append('file', file);

      const { code, data, msg } = await uploadFileNoCompressApi(formData);
      if (code == 200) {
        this.form.url = data;
        this.$message.success(this.$t('imported_successfully'));
      } else {
        this.$message.warning(msg);
      }
    },

    downloadTemp() {
      const tHeader = ['MID', 'nickname', 'dollars or coin', 'account'];
      exportJsonToExcel(tHeader, [], ''); // 导出文件
    },

    // 隐藏此刻按钮
    hideNowBtn() {
      this.$nextTick(() => {
        const arr = document.querySelectorAll('.el-button--text');
        for (let i = 0; i < arr.length; i++) {
          arr[i].style = 'display:none;';
        }
      });
    },

    beforeAdd() {
      const { url, name, rewardTimeStr, type } = this.form;
      if (!name || name.trim() == '') {
        this.$message.warning(this.$t('please_enter_the_event_name'));
        return;
      }

      if (!url) {
        this.$message.warning(this.$t('import_winners_list'));
        return;
      }

      if (
        type == TYPE_MAP.AUTO &&
        (!rewardTimeStr || isPast(new Date(rewardTimeStr)))
      ) {
        this.$message.warning(this.$t('prize_must_be_issued_in_the_future'));
        return;
      }

      this.confirmAdd();
    },

    viewErrorArray(array) {
      this.errorArray = array;
      this.show.error = true;
    },

    async confirmAdd() {
      if (this.btnLoading) return;
      this.btnLoading = true;
      const { name, msgType, type, rewardTimeStr } = this.form;

      const msgMap = {
        1: `尊敬的用户，恭喜你在 【${name}】 中获得【%s】的奖励，请前往APP钱包查询，感谢你的支持。`,
        2: `Dear users, congratulations on getting the reward of 【%s】 in 【${name}】, please go to your APP wallet to check, thank you for your support.`,
        3: `អ្នកប្រើប្រាស់ជាទីស្រលាញ់ អបអរសាទរ ក្នុងកម្មវិធី 【${name}】 អ្នកបានឈ្នះរង្វាន់ចំនួន 【%s】 សូមចូលពិនិត្យមើលកាបូបលុយក្នុង TNAOT APP របស់អ្នក សូមអរគុណ។`
      };
      const msg = msgMap[msgType];
      const query = {
        ...this.form,
        rewardTimeStr: type == TYPE_MAP.Manual ? null : rewardTimeStr,
        msg
      };

      try {
        const { state, error_msg } = await rewardAddApi(query);
        if (state == 1) {
          this.$message.success(this.$t('operate_successfully'));
          this.show.add = false;
          this.getList();
        } else {
          this.$message.warning(error_msg);
        }
      } finally {
        this.btnLoading = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 15px;

  .top-search {
    margin: 10px 0;

    label {
      font-size: 12px;
      font-weight: 400;
      margin-right: 5px;
    }
  }

  .import-btn {
    display: inline-block;
  }

  .tip {
    font-size: 12px;
    color: #7f7f7f;
  }

  .w-120 {
    width: 120px;
  }

  .w-180 {
    width: 180px;
  }

  .w-240 {
    width: 240px;
  }

  .w-400 {
    width: 400px;
  }

  .p-t-20 {
    padding-top: 20px;
  }

  .m-l-10 {
    margin-left: 10px;
  }

  .fr {
    float: right;
    padding-top: 20px;
  }

  .details-img {
    display: inline-block;
    width: 298px;
    height: 224px;
    object-fit: cover;
    margin: 0 20px 20px 0;
  }

  .error-item {
    display: inline-block;
    width: 100px;
    height: 28px;
    font-size: 14px;
    line-height: 28px;
    text-align: center;
    border: 1px solid #ccc;
    margin: 0 10px 10px ;
  }
}
</style>
